package a6polo.net.tencen.qzone;

import java.net.URLEncoder;

import net.a6polo.a6poloweibo.MainTabActivity;
import net.a6polo.a6poloweibo.R;
import net.a6polo.a6poloweibo.util.A6poloUtil;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class QzoneIndexActivity extends Activity {

	private WebView webView;
	private String access_token = null;

	String authUrl = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_renren_index);

		webView = (WebView) findViewById(R.id.web);

		String redirectUri = URLEncoder.encode(QzoneApi.redirectUri);
		authUrl = "https://graph.qq.com/oauth2.0/authorize?response_type=token&client_id=" + QzoneApi.clientId
				+ "&redirect_uri=" + redirectUri + "&state=test&scope=" + QzoneApi.scope + "&display=mobile&g_ut=2";

		Log.d("a6polo", "---------qzone authUrl:" + authUrl);

		bindViews(authUrl);

	}

	private void bindViews(String url) {
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);
		webView.loadUrl(url);
		webView.requestFocusFromTouch();

		WebViewClient wvc = new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				// 人人网用户名和密码验证通过后，刷新页面时即可返回accessToken
				String reUrl = webView.getUrl();

				Log.d("a6polo", "reUrl:" + reUrl);
				if (reUrl.indexOf("access_token") != -1) {
					// 截取url中的accessToken
					int startPos = reUrl.indexOf("access_token=") + 13;
					int endPos = reUrl.indexOf("&expires_in");
					access_token = reUrl.substring(startPos, endPos);

					Log.d("a6polo", "---------qzone access_token:" + access_token);
					A6poloUtil.saveToPreferences(QzoneIndexActivity.this, "qq_token", "accessToken", access_token);
					new Thread(new Runnable() {
						@Override
						public void run() {
							QzoneApi qzoneApi = new QzoneApi(QzoneIndexActivity.this);

							String openid = qzoneApi.getOpenid(access_token);
							if (null != openid) {
								Log.d("a6polo", "---------qzone openid:" + openid);
								A6poloUtil.saveToPreferences(QzoneIndexActivity.this, "qq_token", "openId", openid);
							}
						}
					}).start();

					Toast.makeText(QzoneIndexActivity.this, "QQ验证成功", Toast.LENGTH_SHORT).show();

					Intent intent = new Intent();
					intent.setClass(QzoneIndexActivity.this, MainTabActivity.class);
					startActivity(intent);

					finish();
				}
			}
		};
		webView.setWebViewClient(wvc);

	}

}
